<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px" v-show="showSearch">
      <el-form-item label="定位器编码" prop="locatorCode">
        <el-input
          v-model="queryParams.locatorCode"
          placeholder="请输入定位器编码"
          clearable
          size="small"
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      
      <el-form-item label="器具编码" prop="containerCode">
        <el-input
          v-model="queryParams.containerCode"
          placeholder="请输入器具编码"
          clearable
          size="small"
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      
      <el-form-item label="上传时间" prop="uploadTimeRange">
        <el-date-picker
          v-model="queryParams.uploadTimeRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          size="small"
          style="width: 320px"
        />
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
        >导出</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['pack:location:log:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleRefresh"
        >刷新</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据列表区 -->
    <el-table
      v-loading="loading"
      :data="logList"
      row-key="logId"
      :default-sort="{prop: 'uploadTime', order: 'descending'}"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="45" align="center" />
      
      <el-table-column label="日志ID" prop="logId" width="80" align="center" />
      
      <el-table-column label="定位器编码" prop="locatorCode" width="120" align="center">
        <template slot-scope="scope">
          <el-link type="primary" @click="handleLocatorDetail(scope.row)">
            {{ scope.row.locatorCode }}
          </el-link>
        </template>
      </el-table-column>
      
      <el-table-column label="器具编码" prop="containerCode" width="120" align="center">
        <template slot-scope="scope">
          <el-link type="success" @click="handleContainerDetail(scope.row)" v-if="scope.row.containerCode">
            {{ scope.row.containerCode }}
          </el-link>
          <span v-else class="text-muted">未绑定</span>
        </template>
      </el-table-column>
      
      <el-table-column label="上传时间" prop="uploadTime" width="160" align="center" sortable>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.uploadTime) }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="位置信息" min-width="220" align="center">
        <template slot-scope="scope">
          <div class="location-info">
            <div class="coordinates">
              <i class="el-icon-location"></i>
              {{ scope.row.latitude }}, {{ scope.row.longitude }}
            </div>
            <div class="address" v-if="scope.row.uploadAddress">
              {{ scope.row.uploadAddress }}
            </div>
          </div>
        </template>
      </el-table-column>
      
      <el-table-column label="电池电量" prop="batteryLevel" width="100" align="center" sortable>
        <template slot-scope="scope">
          <el-progress
            :percentage="scope.row.batteryLevel"
            :color="getBatteryColor(scope.row.batteryLevel)"
            :stroke-width="10"
            :show-text="false"
          />
          <div class="battery-text">{{ scope.row.batteryLevel }}%</div>
        </template>
      </el-table-column>
      
      <el-table-column label="温度" prop="temperature" width="80" align="center" sortable>
        <template slot-scope="scope">
          <span :class="getTemperatureClass(scope.row.temperature)">
            {{ scope.row.temperature }}°C
          </span>
        </template>
      </el-table-column>
      
      <el-table-column label="湿度" prop="humidity" width="80" align="center" sortable>
        <template slot-scope="scope">
          <span>{{ scope.row.humidity }}%</span>
        </template>
      </el-table-column>
      
      <el-table-column label="震动等级" prop="shockLevel" width="110" align="center" sortable>
        <template slot-scope="scope">
          <el-tag :type="getShockLevelType(scope.row.shockLevel)" size="mini">
            {{ getShockLevelText(scope.row.shockLevel) }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column label="操作" align="center" width="80" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['pack:location:log:query']"
          >详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 详情抽屉 -->
    <el-drawer
      title="定位日志详情"
      :visible.sync="detailDrawer"
      direction="rtl"
      size="50%"
      :before-close="handleDetailClose"
      custom-class="drawer-container"
    >
      <div class="drawer-content">
        <log-detail
          v-if="detailDrawer"
          :log-id="currentLogId"
          @close="handleDetailClose"
        />
      </div>
    </el-drawer>

    <!-- 新增/编辑抽屉 -->
    <el-drawer
      :title="form.logId ? '编辑定位日志' : '新增定位日志'"
      :visible.sync="formDrawer"
      direction="rtl"
      size="50%"
      :before-close="handleFormClose"
      custom-class="drawer-container"
    >
      <div class="drawer-content">
        <log-form
          v-if="formDrawer"
          :form="form"
          @submit="handleSubmit"
          @cancel="handleFormClose"
        />
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { listLocationLog, getLocationLog, addLocationLog, updateLocationLog, delLocationLog, exportLocationLog, searchLocationLog } from "@/api/pack/locationLog";
import LogDetail from './components/LogDetail';
import LogForm from './components/LogForm';

export default {
  name: "LocationLog",
  components: {
    LogDetail,
    LogForm
  },
  data() {
    return {
      // 加载状态
      loading: true,
      exportLoading: false,
      
      // 显示状态
      showSearch: true,
      detailDrawer: false,
      formDrawer: false,
      
      // 数据列表
      logList: [],
      total: 0,
      
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        locatorCode: null,
        containerCode: null,
        uploadTimeRange: [],
        batteryRange: [0, 100],
        shockLevel: null,
        uploadAddress: null
      },
      
      // 表单数据
      form: {},
      
      // 当前操作的日志ID
      currentLogId: null,
      
      // 选中的行数据
      selectedRows: []
    }
  },
  
  created() {
    this.getList()
  },
  
  methods: {
    // 查询列表
    getList() {
      this.loading = true
      
      // 判断是否使用高级搜索
      if (this.hasAdvancedSearch()) {
        const params = this.getAdvancedSearchParams();
        searchLocationLog(params).then(response => {
          this.logList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      } else {
        // 使用普通搜索
        listLocationLog(this.queryParams).then(response => {
          this.logList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      }
    },
    
    // 判断是否使用高级搜索
    hasAdvancedSearch() {
      return (
        this.queryParams.uploadTimeRange && this.queryParams.uploadTimeRange.length === 2 ||
        this.queryParams.batteryRange && (this.queryParams.batteryRange[0] > 0 || this.queryParams.batteryRange[1] < 100) ||
        this.queryParams.shockLevel !== null
      );
    },
    
    // 获取高级搜索参数
    getAdvancedSearchParams() {
      return {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        locatorCode: this.queryParams.locatorCode,
        containerCode: this.queryParams.containerCode,
        startTime: this.queryParams.uploadTimeRange?.[0],
        endTime: this.queryParams.uploadTimeRange?.[1],
        minBatteryLevel: this.queryParams.batteryRange[0],
        maxBatteryLevel: this.queryParams.batteryRange[1],
        shockLevel: this.queryParams.shockLevel,
        uploadAddress: this.queryParams.uploadAddress
      };
    },
    
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    
    // 重置按钮操作
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.batteryRange = [0, 100];
      this.queryParams.uploadTimeRange = [];
      this.handleQuery();
    },
    
    // 新增按钮操作
    handleAdd() {
      this.form = {};
      this.formDrawer = true;
    },
    
    // 详情按钮操作
    handleDetail(row) {
      this.currentLogId = row.logId;
      this.detailDrawer = true;
    },
    
    // 刷新操作
    handleRefresh() {
      this.getList();
    },
    
    // 导出操作
    handleExport() {
      this.exportLoading = true;
      
      // 构建导出参数
      const exportParams = {
        locatorCode: this.queryParams.locatorCode,
        containerCode: this.queryParams.containerCode,
        startTime: this.queryParams.uploadTimeRange?.[0],
        endTime: this.queryParams.uploadTimeRange?.[1],
        minBatteryLevel: this.queryParams.batteryRange[0],
        maxBatteryLevel: this.queryParams.batteryRange[1],
        shockLevel: this.queryParams.shockLevel,
        uploadAddress: this.queryParams.uploadAddress,
        exportFields: [
          "locatorCode",
          "containerCode", 
          "uploadTime",
          "latitude",
          "longitude",
          "uploadAddress",
          "batteryLevel",
          "temperature",
          "humidity",
          "shockLevel"
        ]
      };
      
      this.download('/pack/location/log/export', exportParams, `定位日志_${new Date().getTime()}.xlsx`);
      this.exportLoading = false;
    },
    
    // 获取电池颜色
    getBatteryColor(level) {
      if (level >= 80) return '#67c23a';
      if (level >= 50) return '#e6a23c';
      if (level >= 20) return '#f56c6c';
      return '#909399';
    },
    
    // 获取温度样式类
    getTemperatureClass(temp) {
      if (temp < 0) return 'temp-cold';
      if (temp > 35) return 'temp-hot';
      return 'temp-normal';
    },
    
    // 获取震动等级类型
    getShockLevelType(level) {
      const types = ['', 'success', 'info', 'warning', 'danger', 'danger'];
      return types[level] || 'info';
    },
    
    // 获取震动等级文本
    getShockLevelText(level) {
      const texts = ['', '轻微', '一般', '中等', '强烈', '剧烈'];
      return texts[level] || '未知';
    },
    
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    
    // 定位器详情
    handleLocatorDetail(row) {
      const { locatorId } = row;
      this.$router.push({ path: '/pack/locator', query: { locatorId } });
    },
    
    // 器具详情
    handleContainerDetail(row) {
      const { containerId } = row;
      if (containerId) {
        this.$router.push({ path: '/pack/container', query: { containerId } });
      }
    },
    
    // 详情抽屉关闭
    handleDetailClose() {
      this.detailDrawer = false;
    },
    
    // 表单抽屉关闭
    handleFormClose() {
      this.formDrawer = false;
    },
    
    // 表单提交
    handleSubmit(formData) {
      if (formData.logId) {
        // 编辑
        updateLocationLog(formData).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.formDrawer = false;
          this.getList();
        });
      } else {
        // 新增
        addLocationLog(formData).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.formDrawer = false;
          this.getList();
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.location-info {
  .coordinates {
    font-size: 12px;
    color: #666;
    margin-bottom: 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  
  .address {
    font-size: 12px;
    color: #999;
    line-height: 1.4;
    margin-top: 4px;
    word-break: break-all;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
}

.battery-text {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.temp-cold {
  color: #409eff;
}

.temp-normal {
  color: #67c23a;
}

.temp-hot {
  color: #f56c6c;
}

.text-muted {
  color: #c0c4cc;
}

.drawer-container {
  position: relative;
  height: 100%;
}

.drawer-content {
  padding: 20px;
  height: calc(100% - 60px);
  overflow-y: auto;
}

.drawer-footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  padding: 10px 20px;
  background-color: #fff;
  border-top: 1px solid #e8e8e8;
  text-align: right;
}

@media (max-width: 768px) {
  .el-form--inline .el-form-item {
    display: block;
    margin-bottom: 10px;
  }
  
  .el-table {
    font-size: 12px;
  }
}
</style> 